package com.railway.app;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import static com.railway.app.Payment.referenceNo;
import com.railway.utils.CustomTableModel;
import com.railway.classes.Ticket;
import com.railway.utils.RestServer;
import com.railway.utils.Toast;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
 *
 * @author Moofie
 */
public class SeatDialog extends javax.swing.JDialog {
    //public Ticket ticket = new Ticket();
    private int count=0;
    private int aCount = 0;
    private double total = 0;
    private double discount = 0;
    private double totalDiscounted = 0;
    public static String[] tickets = new String[56];
    private String[] bookedSeat = new String[56];
    JToggleButton[] jtbSeat = new JToggleButton[56];
    private ArrayList<String> colName;
    private ArrayList<ArrayList<Object>> rowData;
    private CustomTableModel ctmModel;
    private String[] list = {"Adult", "Child"};
    private JComboBox jcb = new JComboBox(list);
    DecimalFormat df = new DecimalFormat("#.##");
    private double tempDiscount = 0;
    
    
    private JSONObject json;
    private JSONArray jsonArray;
    /**
     * Creates new form SeatDialog
     */
    public SeatDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initializeTable();
        tempDiscount = (1 - getTodayDiscount())*100;
        jlblPromotion.setText(""+getTodayPromotionName());
        jlblRate.setText(""+df.format(tempDiscount)+"%");
        jlblTicketPrice.setText("RM "+df.format(Ticket.getTicketPrice()));
        setSampleButton();
        initializeSelectCoachTable();
    }

    private void setSampleButton(){
        jtbSampleAvailable.setBackground(Color.pink);
        jtbSampleBooked.setEnabled(false);
    }
    public static String[] getTickets() {
        return tickets;
    }

    public static void setTickets(String[] tickets) {
        SeatDialog.tickets = tickets;
    }
    
     
     private void initializeTable() {
        new Thread() {
            @Override
            public void run() {
                colName = new ArrayList<>();
                colName.add("SeatID");
                colName.add("Seat Name");
                colName.add("Price");
                colName.add("Discount");
                String data = RestServer.httpGet("staffDetail", "");
                try {
                    json = new JSONObject(data);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                            rowData = new ArrayList<>();
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < 1; i++) {
                                ArrayList<Object> temp = new ArrayList<>();
                                temp.add("a");
                                temp.add("b");
                                temp.add("c");
                                temp.add("d");
                                rowData.add(temp);
                            }
                            ctmModel = new CustomTableModel(colName, rowData);
                            jtbSeatDetails.setModel(ctmModel);
                            ctmModel.removeRow(0);
                        
                    } else {
                        Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
                    }
                } catch (JSONException ex) {
                    System.out.println(ex);
                }
            }
        }.start();
    }

     private void accumulateTotal(){
         total = 0;
        for(int i = 0 ; i < ctmModel.getRowCount() ; i++){
            total += Double.parseDouble((String)ctmModel.getValueAt(i, 2));
        }
     }
     
      private void accumulateDiscountTotal(){
         totalDiscounted = 0;
        for(int i = 0 ; i < ctmModel.getRowCount() ; i++){
            totalDiscounted += Double.parseDouble((String)ctmModel.getValueAt(i, 3));
        }
     }
      
    private double getTodayDiscount(){
        double rate = 1.0;
        String a = RestServer.httpGet("discounts", "");
        try{
            JSONObject json = new JSONObject(a);
            JSONArray content = json.getJSONArray("content");
            rate = Double.parseDouble(content.getJSONObject(0).getString("rate"));
            Ticket.setDiscount(rate);
            Ticket.setDiscountId(""+content.getJSONObject(0).getString("discountId"));
        }catch(JSONException ex){
            System.out.println(ex);
            return rate;
        }
        return rate;
    }
    
    private String getTodayPromotionName(){
        String promotion = null;
        String a = RestServer.httpGet("discounts", "");
        try{
            JSONObject json = new JSONObject(a);
            JSONArray ja = json.getJSONArray("content");
            //System.out.println(ja.getJSONObject(0).get("rate"));
            promotion = ja.getJSONObject(0).get("type").toString();
        }catch(JSONException ex){
            //System.out.println(ex);
            promotion = "-";
            return promotion;
        }
        return promotion;
    }
    
    private void initializeSelectCoachTable(){
        total=0;
        aCount=0;
        totalDiscounted = 0 ;
        jlblTicketNo.setText(""+aCount);
        jlblTotal.setText(""+total);
        jlblDiscount.setText(""+df.format(totalDiscounted));
        for(int i =0 ; i < ctmModel.getRowCount(); i++){
            ctmModel.removeRow(i);
        }
        initializeTable();
        ctmModel.fireTableDataChanged();

        jpSeat.removeAll();
        aCount=0;
        String shid = Ticket.getShid();
        String dates = Ticket.getBookedDate();
        String coach = "A";
        String a = RestServer.httpGet("coachMap", jcbCoach.getSelectedItem().toString());
        String b = RestServer.httpGet("coachMapBooked", coach+"/"+shid+"/"+dates);
        System.out.println(a);
        System.out.println(b);
        try {
            JSONObject json = new JSONObject(a);
            JSONArray content = json.getJSONArray("content");
            JSONObject jsonb = new JSONObject(b);
            JSONArray contentB = jsonb.getJSONArray("content");

            int length = content.length();
            int y = 0;
            GridLayout layout = new GridLayout(14,4);
                layout.setHgap(10);
                layout.setVgap(3);
            jpSeat.setLayout(layout);

            for(int k = 0 ; k < contentB.length() ; k++){
                bookedSeat[k] = contentB.getJSONObject(k).getString("seatid");
                System.out.println(bookedSeat[k]);
            }

            for(int i = 0 ; i < 56 ; i++){
                if(content.getJSONObject(i).getString("seatid").equals(bookedSeat[y])){
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jpSeat.add(jtbSeat[i]);
                    jtbSeat[i].setEnabled(false);
                    y++;
                }else{
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jtbSeat[i].setBackground(Color.pink);
                    jtbSeat[i].setEnabled(true);
                    jpSeat.add(jtbSeat[i]);
                
                
                jtbSeat[i].addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e){
                        JToggleButton jtb = (JToggleButton) e.getSource();
                        if(jtb.isSelected()){
                            if(aCount>9){
                                Toast.makeText(getParent(), "Max of 10 ticket allow per-transaction", Toast.LENGTH_LONG).display();
                                jtb.setSelected(false);
                            }else{
                                double ticketPrice = Ticket.getTicketPrice();
                                double discountRate = 0;
                                double promotionRate = 1- getTodayDiscount();
                                String rate = "0%";
                                JOptionPane.showMessageDialog(null, jcb, "Select Option", JOptionPane.QUESTION_MESSAGE);
                                if(jcb.getSelectedItem().toString().equals("Child")){
                                    discountRate = 0.8 - promotionRate;
                                    rate = "20%";
                                    discount = ticketPrice * (1.0-discountRate);
                                    ticketPrice = ticketPrice * discountRate;
                                }else{
                                    discountRate = 1.0 - promotionRate;
                                    rate = "0%";
                                    discount = ticketPrice * (1.0-discountRate);
                                    ticketPrice = ticketPrice * discountRate;
                                }
                                

                                jtb.setBackground(Color.green);
                                String[] aSplit = e.getActionCommand().split("->");
                                ArrayList<Object> temps = new ArrayList<>();
                                temps.add(aSplit[0]);
                                temps.add(aSplit[1]);
                                temps.add(""+df.format(ticketPrice));
                                temps.add(""+df.format(discount));
                                ctmModel.addRow(temps);

                                aCount++;
                                accumulateTotal();
                                accumulateDiscountTotal();
                                jlblTicketNo.setText(""+aCount);
                                jlblTotal.setText(""+df.format(total));
                                jlblDiscount.setText(""+df.format(totalDiscounted));
                            }
                            
                        }else{
                            jtb.setBackground(Color.pink);
                            
                            String[] bSplit = e.getActionCommand().split("->");
                            for(int i = 0 ; i < ctmModel.getRowCount() ;i++){
                                if(bSplit[0].equals(jtbSeatDetails.getModel().getValueAt(i, 0))){
                                    ctmModel.removeRow(i);
                                    ctmModel.fireTableDataChanged();
                                }
                            }
                            accumulateTotal();
                            accumulateDiscountTotal();
                            aCount--;
                            jlblTicketNo.setText(""+aCount);
                            jlblTotal.setText(""+df.format(total));
                            jlblDiscount.setText(""+df.format(totalDiscounted));
                        }
                    }
                });
            }
            }
            this.pack();
            jpSeat.setVisible(true);
            jpSeat.revalidate();
            jpSeat.repaint();

        } catch (JSONException ex) {
            JOptionPane.showMessageDialog(null,"Error: "+ex);
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpMainSeat = new javax.swing.JPanel();
        jcbCoach = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jpSeat = new javax.swing.JPanel();
        jpSeatInfo = new javax.swing.JPanel();
        jspTableScroller = new javax.swing.JScrollPane();
        jtbSeatDetails = new javax.swing.JTable();
        jbtCheckOut = new javax.swing.JButton();
        jbtBack = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jlblTicketNo = new javax.swing.JLabel();
        jlblTotal = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jlblDiscount = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jlblPromotion = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jlblRate = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jlblTicketPrice = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jtbSampleBooked = new javax.swing.JButton();
        jtbSampleAvailable = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);

        jpMainSeat.setBackground(new java.awt.Color(46, 204, 113));
        jpMainSeat.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 51), 2));
        jpMainSeat.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jpMainSeat.setMaximumSize(new java.awt.Dimension(870, 440));
        jpMainSeat.setMinimumSize(new java.awt.Dimension(870, 440));
        jpMainSeat.setName(""); // NOI18N
        jpMainSeat.setPreferredSize(new java.awt.Dimension(870, 440));
        jpMainSeat.setRequestFocusEnabled(false);

        jcbCoach.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A", "B", "C", "D", "E", "F" }));
        jcbCoach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbCoachActionPerformed(evt);
            }
        });

        jLabel1.setText("Coach");

        javax.swing.GroupLayout jpSeatLayout = new javax.swing.GroupLayout(jpSeat);
        jpSeat.setLayout(jpSeatLayout);
        jpSeatLayout.setHorizontalGroup(
            jpSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 376, Short.MAX_VALUE)
        );
        jpSeatLayout.setVerticalGroup(
            jpSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 405, Short.MAX_VALUE)
        );

        jspTableScroller.setPreferredSize(new java.awt.Dimension(100, 100));

        jtbSeatDetails.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbSeatDetails.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jtbSeatDetails.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbSeatDetailsMouseClicked(evt);
            }
        });
        jspTableScroller.setViewportView(jtbSeatDetails);

        jbtCheckOut.setText("CheckOut");
        jbtCheckOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCheckOutActionPerformed(evt);
            }
        });

        jbtBack.setText("Back");
        jbtBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtBackActionPerformed(evt);
            }
        });

        jLabel2.setText("No. Tickets");

        jLabel3.setText("Total");

        jlblTicketNo.setText("0");

        jlblTotal.setText("0");

        jLabel4.setText("Discount");

        jlblDiscount.setText("0");

        jLabel5.setText("Promotion");

        jlblPromotion.setText("None");

        jLabel7.setText("Rate");

        jlblRate.setText("0");

        jLabel6.setText("Ticket Price");

        jlblTicketPrice.setText("0");

        javax.swing.GroupLayout jpSeatInfoLayout = new javax.swing.GroupLayout(jpSeatInfo);
        jpSeatInfo.setLayout(jpSeatInfoLayout);
        jpSeatInfoLayout.setHorizontalGroup(
            jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jspTableScroller, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jpSeatInfoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpSeatInfoLayout.createSequentialGroup()
                        .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jbtBack, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(jpSeatInfoLayout.createSequentialGroup()
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(20, 20, 20)
                                    .addComponent(jlblTicketNo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jbtCheckOut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jpSeatInfoLayout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jlblDiscount, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
                                    .addComponent(jlblTotal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(jpSeatInfoLayout.createSequentialGroup()
                        .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlblPromotion, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlblRate, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlblTicketPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 14, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jpSeatInfoLayout.setVerticalGroup(
            jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpSeatInfoLayout.createSequentialGroup()
                .addComponent(jspTableScroller, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jlblPromotion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jlblRate))
                .addGap(26, 26, 26)
                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jlblTotal)
                    .addComponent(jlblTicketPrice)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jlblDiscount)
                    .addComponent(jLabel2)
                    .addComponent(jlblTicketNo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpSeatInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtBack, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtCheckOut, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jtbSampleBooked.setText("Booked");

        jtbSampleAvailable.setText("Available");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jtbSampleAvailable, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jtbSampleBooked, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jtbSampleAvailable)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jtbSampleBooked)
                .addContainerGap(53, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jpMainSeatLayout = new javax.swing.GroupLayout(jpMainSeat);
        jpMainSeat.setLayout(jpMainSeatLayout);
        jpMainSeatLayout.setHorizontalGroup(
            jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpMainSeatLayout.createSequentialGroup()
                .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpMainSeatLayout.createSequentialGroup()
                        .addGap(230, 230, 230)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbCoach, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpMainSeatLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jpSeat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(24, 24, 24)
                .addComponent(jpSeatInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(22, 22, 22))
        );
        jpMainSeatLayout.setVerticalGroup(
            jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpMainSeatLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpMainSeatLayout.createSequentialGroup()
                        .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jcbCoach, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jpSeat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jpSeatInfo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 870, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jpMainSeat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 458, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jpMainSeat, javax.swing.GroupLayout.PREFERRED_SIZE, 458, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents



    private void jcbCoachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbCoachActionPerformed
        //System.out.println(ctmModel.getRowCount());
        total=0;
        aCount=0;
        totalDiscounted = 0 ;
        jlblTicketNo.setText(""+aCount);
        jlblTotal.setText(""+total);
        jlblDiscount.setText(""+df.format(totalDiscounted));
        for(int i =0 ; i < ctmModel.getRowCount(); i++){
            ctmModel.removeRow(i);
        }
        initializeTable();
        ctmModel.fireTableDataChanged();

        jpSeat.removeAll();
        aCount=0;
        String shid = Ticket.getShid();
        String dates = Ticket.getBookedDate();
        String coach = jcbCoach.getSelectedItem().toString();
        String a = RestServer.httpGet("coachMap", jcbCoach.getSelectedItem().toString());
        String b = RestServer.httpGet("coachMapBooked", coach+"/"+shid+"/"+dates);
        System.out.println(a);
        System.out.println(b);
        System.out.println(coach);
        System.out.println(shid);
        System.out.println(dates);
        
        try {
            JSONObject json = new JSONObject(a);
            JSONArray content = json.getJSONArray("content");
            JSONObject jsonb = new JSONObject(b);
            JSONArray contentB = jsonb.getJSONArray("content");

            int length = content.length();
            int y = 0;
            GridLayout layout = new GridLayout(14,4);
                layout.setHgap(10);
                layout.setVgap(3);
            jpSeat.setLayout(layout);

            for(int k = 0 ; k < contentB.length() ; k++){
                bookedSeat[k] = contentB.getJSONObject(k).getString("seatid");
                System.out.println(bookedSeat[k]);
            }

            for(int i = 0 ; i < 56 ; i++){
                if(content.getJSONObject(i).getString("seatid").equals(bookedSeat[y])){
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jpSeat.add(jtbSeat[i]);
                    jtbSeat[i].setEnabled(false);
                    y++;
                }else{
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jtbSeat[i].setBackground(Color.pink);
                    jtbSeat[i].setEnabled(true);
                    jpSeat.add(jtbSeat[i]);
                
                
                jtbSeat[i].addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e){
                        JToggleButton jtb = (JToggleButton) e.getSource();
                        if(jtb.isSelected()){
                            if(aCount>9){
                                Toast.makeText(getParent(), "Max of 10 ticket allow per-transaction", Toast.LENGTH_LONG).display();
                                jtb.setSelected(false);
                            }else{
                                double ticketPrice = Ticket.getTicketPrice();
                                double discountRate = 0;
                                double promotionRate = 1- getTodayDiscount();
                                String rate = "0%";
                                JOptionPane.showMessageDialog(null, jcb, "Select Option", JOptionPane.QUESTION_MESSAGE);
                                if(jcb.getSelectedItem().toString().equals("Child")){
                                    discountRate = 0.8 - promotionRate;
                                    rate = "20%";
                                    discount = ticketPrice * (1.0-discountRate);
                                    ticketPrice = ticketPrice * discountRate;
                                }else{
                                    discountRate = 1.0 - promotionRate;
                                    rate = "0%";
                                    discount = ticketPrice * (1.0-discountRate);
                                    ticketPrice = ticketPrice * discountRate;
                                }
                                

                                jtb.setBackground(Color.green);
                                String[] aSplit = e.getActionCommand().split("->");
                                ArrayList<Object> temps = new ArrayList<>();
                                temps.add(aSplit[0]);
                                temps.add(aSplit[1]);
                                temps.add(""+df.format(ticketPrice));
                                temps.add(""+df.format(discount));
                                ctmModel.addRow(temps);

                                aCount++;
                                accumulateTotal();
                                accumulateDiscountTotal();
                                jlblTicketNo.setText(""+aCount);
                                jlblTotal.setText(""+df.format(total));
                                jlblDiscount.setText(""+df.format(totalDiscounted));
                            }
                            
                        }else{
                            jtb.setBackground(Color.pink);
                            
                            String[] bSplit = e.getActionCommand().split("->");
                            for(int i = 0 ; i < ctmModel.getRowCount() ;i++){
                                if(bSplit[0].equals(jtbSeatDetails.getModel().getValueAt(i, 0))){
                                    ctmModel.removeRow(i);
                                    ctmModel.fireTableDataChanged();
                                }
                            }
                            accumulateTotal();
                            accumulateDiscountTotal();
                            aCount--;
                            jlblTicketNo.setText(""+aCount);
                            jlblTotal.setText(""+df.format(total));
                            jlblDiscount.setText(""+df.format(totalDiscounted));
                        }
                    }
                });
            }
            }
            this.pack();
            jpSeat.setVisible(true);
            jpSeat.revalidate();
            jpSeat.repaint();

        } catch (JSONException ex) {
            JOptionPane.showMessageDialog(null,"Error: "+ex);
        }
    }//GEN-LAST:event_jcbCoachActionPerformed

    private void jbtCheckOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCheckOutActionPerformed
        if(aCount==0){
            Toast.makeText(getParent(), "Please select seat", Toast.LENGTH_LONG).display();
        }else{
            count = 0;
            for(int i = 0; i < 56; i++){
                if(jtbSeat[i].isSelected()){
                    tickets[count] = jtbSeat[i].getActionCommand();
                    System.out.println(tickets[count]);
                    count++;
                    
                }
            }
            if(count==0){
                Toast.makeText(getParent(), "Please select seat", Toast.LENGTH_LONG).display();
            }else if(count > 10){
                Toast.makeText(getParent(), "Only 10 ticket allow per transaction", Toast.LENGTH_LONG).display();
            }else{

                Ticket.setNoTickets(Integer.parseInt(jlblTicketNo.getText()));
                System.out.println("No of Tickets:"+Ticket.getNoTickets());
                Ticket.setTotal(Double.parseDouble(jlblTotal.getText()));
                Ticket.setDiscount(Double.parseDouble(jlblDiscount.getText()));
                Payment payment = new Payment(null,true,this);
                payment.show();
  
            }
        }
    }//GEN-LAST:event_jbtCheckOutActionPerformed

    private void jbtBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtBackActionPerformed
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.dispose();
    }//GEN-LAST:event_jbtBackActionPerformed

    private void jtbSeatDetailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbSeatDetailsMouseClicked
        int selectedRow = jtbSeatDetails.getSelectedRow();
        String id = (String)jtbSeatDetails.getModel().getValueAt(selectedRow, 0);
        String name = (String)jtbSeatDetails.getModel().getValueAt(selectedRow, 1);
        
        Object IdName = (Object)id+"->"+name;
        
        System.out.println(IdName);
        for(int i = 0 ; i < 56 ; i++){
            System.out.println(jtbSeat[i].getActionCommand() + " " + IdName);
            if(jtbSeat[i].getActionCommand().equals(IdName)){

                jtbSeat[i].setSelected(false);
                jtbSeat[i].setBackground(Color.pink);
                ctmModel.removeRow(selectedRow);
                ctmModel.fireTableDataChanged();
                
                accumulateTotal();
                accumulateDiscountTotal();
                aCount--;
                jlblTicketNo.setText(""+aCount);
                jlblTotal.setText(""+total);
                jlblDiscount.setText(""+totalDiscounted);
            }
        }
    }//GEN-LAST:event_jtbSeatDetailsMouseClicked

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbtBack;
    private javax.swing.JButton jbtCheckOut;
    private javax.swing.JComboBox jcbCoach;
    private javax.swing.JLabel jlblDiscount;
    private javax.swing.JLabel jlblPromotion;
    private javax.swing.JLabel jlblRate;
    private javax.swing.JLabel jlblTicketNo;
    private javax.swing.JLabel jlblTicketPrice;
    private javax.swing.JLabel jlblTotal;
    private javax.swing.JPanel jpMainSeat;
    private javax.swing.JPanel jpSeat;
    private javax.swing.JPanel jpSeatInfo;
    private javax.swing.JScrollPane jspTableScroller;
    private javax.swing.JButton jtbSampleAvailable;
    private javax.swing.JButton jtbSampleBooked;
    private javax.swing.JTable jtbSeatDetails;
    // End of variables declaration//GEN-END:variables
}
